<script>
//  图层管理模块
import { mapGetters, mapMutations } from 'vuex';
import * as helps from '@/utils/helps';
import mapManager from '../mapManager.js';
import config from 'config';
import DataTree from '../../workspace/editor/mapeditor/DataTree';

export default {
  name: 'LayerManager',
  components: { DataTree },
  props: {
    mapData: {
      type: Array,
      default: () => [],
    },
    options: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      //是否处于编辑模式
      editable: false,
      //模态框打开状态
      modalOpened: false,
      //查询关键字
      layerKeyword: '',
      //表格列
      tableColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '服务名称',
          key: 'title',
        },
        {
          title: '类型',
          width: 60,
          key: 'serviceType',
        },
        {
          title: '空间参考',
          key: 'crs',
        },
        {
          title: '服务地址',
          key: 'baseUrl',
        },
        {
          title: '时间',
          key: 'time',
        },
      ],
      //表格数据
      tableData: [],
      //选择的图层
      selectedLayers: [],
      //图层数据
      layerData1: [],
      layerData2: [],
      selected: 'map1',
      layerTotal: 0,
      pageInited: true,
      tableLoading: false,
    };
  },
  computed: {
    ...mapGetters(['controls', 'currentId']),
  },
  watch: {
    options: {
      handler(newVal, oldVal) {
        if (Object.keys(newVal).length !== 0) {
          let serviceList1 = {},
            serviceList2 = {};
          newVal.mode === 'view' ? (this.editable = false) : (this.editable = true);
          if (newVal.data) {
            for (let key in newVal.data) {
              if (newVal.data[key] && key !== 'queryOptions') {
                if (key === 'map_1') this.layerData1 = newVal.data[key];
                if (key === 'map_2') this.layerData2 = newVal.data[key];

                newVal.data[key].forEach(item => {
                  if (item.type === 1) serviceList1[item.name] = item.services;
                  if (item.type === 2) serviceList2[item.name] = item.services;
                });
              }
            }
            this.addMapLayers(serviceList1, 1);
            this.addMapLayers(serviceList2, 2);
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    ...mapMutations({
      updateAppOptions: 'UPDATE_CHART_CONFIG',
    }),
    // 请求服务
    async findAllServices(options) {
      // 服务类型 5,10,11,12,21,22,23
      this.tableLoading = true;
      const response = await api.portal.findServiceList(options);
      this.tableData = [];
      this.treeData = response.data.dataSource;
      response.data.dataSource.forEach(item => {
        if (item.serviceUrl !== '' && item.serviceType === '12') {
          const url = new URL(item.serviceUrl);
          const baseUrl = url.origin + url.pathname;
          this.tableData.push({
            baseUrl,
            time: helps.getLocalTime(item.createTime),
            ...item,
          });
        }
      });
      this.tableLoading = false;
      // 分页总数要重新设置
      if (this.pageInited) {
        this.layerTotal = response.data.pageInfo.totalCount;
      }
    },
    selectTree(data) {
      if (this.newLayer) {
        this.pageInited = true;
        this.childId = data.childId;
        this.queryLayerService(
          '',
          {
            pageIndex: 1,
            pageSize: 10,
          },
          data.childId
        );
      }
    },
    //查询地图服务
    async queryLayerService(
      title = '',
      pageCount = { pageIndex: 1, pageSize: 10 },
      catalogId = config.datavfunction.catalogId
    ) {
      this.newLayer = true;
      const options = {
        objCondition: {
          orgId: this.$user.orgid,
          catalogId, // 目录id（必填）
          ownerId: this.$user.orgid, // 拥有者id（必填）
          getall: 'all', // 递归查数据（必填）
          serviceType: '12,6', // 服务类型（选填）
          title,
        },
        ...pageCount,
        orderby: 'createTime_desc', // 排序（选填）
      };
      this.findAllServices(options);
    },
    //选择地图服务
    openLayerModal(selectedMap) {
      this.selected = selectedMap;
      this.pageInited = true;
      this.queryLayerService('', {
        pageIndex: 1,
        pageSize: 10,
      });
      this.modalOpened = true;
    },
    //设置选中图层
    setSelectedLayers(selection) {
      this.selectedLayers = selection;
    },
    //增加选中图层
    async addLayers() {
      let addWmslayers = {};
      let type;
      const that = this;
      // this.selectedLayers.forEach(async layers => {
      for (let layers of this.selectedLayers) {
        const url = new URL(layers.serviceUrl);
        const layersName = url.searchParams.get('layers');
        const response = await api.db.findService({
          resourceId: layers.resourceId, // 资源id
          serivestatus: 0, // 服务状态(0 开启 1 关闭)
          baseservicetype: 1, // 基础服务
          metadataLayer: layers.metadataLayer, // 元数据图层
        });
        let layerInfo = (addWmslayers[layersName] = []);
        // 暂时修改
        // response.data[0].options = {
        //   styles: 'polygon2',
        // };
        // response.data[1].options = {
        //   styles: 'polygon2',
        // };
        layerInfo = [response.data[0], response.data[1]];
        if (this.selected === 'map_1') {
          this.layerData1.push({
            name: layersName,
            visible: true,
            services: layerInfo,
            type: 1,
            mapBeg: 'map_1',
          });
          type = 1;
        } else {
          that.layerData2.push({
            name: layersName,
            visible: true,
            services: layerInfo,
            type: 2,
            mapBeg: 'map_2',
          });
          type = 2;
        }
      }
      this.addMapLayers(addWmslayers, type);
      this.updateLayerData(this.selected);
    },
    // 浏览服务
    addMapLayers(layerData, type) {
      if (this.mapData.length !== 0) {
        const mapData = this.getMapData(type);
        this.$store.commit(`${mapData[0].mapId}/SET_MAP_SERVICELIST`, layerData);
      }
    },
    // 得到所有的地图
    getMapData(type) {
      return this.mapData.filter(item => item.num === type);
    },
    // 得到地图对象
    getMapObj(layer) {
      const mapData = this.getMapData(layer.type);
      const ogcLayers = this.$store.getters[`${mapData[0].mapId}/ogcLayers`];
      let getlayer = ogcLayers.find(p => p.options.layers == layer.name);
      const mapObj = mapManager.getMapLayer(mapData[0].mapId);
      return { mapObj, getlayer, mapData };
    },
    // 放缩到图层
    zoomToLayer(layer) {
      const getMap = this.getMapObj(layer);
      getMap.mapObj.mapObj[0].$mapObject.fitBounds(getMap.getlayer.options.saveBbox);
    },
    // 设置图层是否可见
    setlayerVisible(layerItem) {
      const getMap = this.getMapObj(layerItem);
      getMap.getlayer.setVisible(layerItem.visible);
      this.updateLayerData(layerItem.mapBeg);
    },
    // 删除图层
    delateLayer(layer) {
      const getMap = this.getMapObj(layer);
      this.$store.commit(`${getMap.mapData[0].mapId}/SET_MAP_GOCLAYER_DELETE`, [layer.name]);
      if (layer.type === 1) {
        helps.removeArrayItemEx(this.layerData1, item => item.name == layer.name);
      } else {
        helps.removeArrayItemEx(this.layerData2, item => item.name == layer.name);
      }
      this.updateLayerData(layer.mapBeg);
    },
    // 更新应用程序配置
    updateLayerData(type) {
      let currentControl = this.controls[this.currentId];
      if (type === 'map_1') {
        currentControl.options.data = {
          [type]: this.layerData1,
          map_2: currentControl.options.data['map_2'],
        };
      } else {
        currentControl.options.data = {
          [type]: this.layerData2,
          map_1: currentControl.options.data['map_1'],
        };
      }
      this.updateAppOptions({ data: { [this.currentId]: currentControl } });
    },
    // 搜索
    searchLayer(title) {
      this.pageInited = true;
      this.queryLayerService(this.layerKeyword, {
        pageIndex: 1,
        pageSize: 10,
      });
    },
    // 分页
    querylayers(pageIdx) {
      this.pageInited = false;
      const pageCount = {
        pageIndex: pageIdx,
        pageSize: 10,
      };
      if (this.childId) {
        this.queryLayerService('', pageCount, this.childId);
      } else {
        this.queryLayerService('', pageCount);
      }
    },
  },
};
</script>

<template>
  <div class="layers-module-wrapper">
    <div
      v-if="editable"
      class="dash-button"
      @click="openLayerModal('map_1')">
      <Icon type="plus-round" />
      给第一个地图添加数据
    </div>
    <div
      v-else
      class="dash-show">图层浏览</div>
    <div class="layer-list-wrapper">
      <div
        v-for="item in layerData1"
        :key="item.name"
        class="layer-item">
        <div class="layer-item-title">
          <Checkbox
            v-model="item.visible"
            @on-change="setlayerVisible(item)"></Checkbox>
          <span>{{ item.name }}</span>
        </div>
        <div class="layer-item-action">
          <Icon
            type="arrow-right-c"
            title="放缩到图层"
            @click.native.stop="zoomToLayer(item)" />
          <Icon
            v-if="editable"
            type="trash-b"
            title="删除图层"
            @click.native.stop="delateLayer(item)" />
        </div>
      </div>
    </div>
    <div
      v-if="editable"
      class="dash-button"
      @click="openLayerModal('map_2')">
      <Icon type="plus-round" />
      给第二个地图添加数据
    </div>
    <div
      v-else
      class="dash-show">图层浏览</div>
    <div class="layer-list-wrapper">
      <div
        v-for="item in layerData2"
        :key="item.name"
        class="layer-item">
        <div class="layer-item-title">
          <Checkbox
            v-model="item.visible"
            @on-change="setlayerVisible(item)"></Checkbox>
          <span>{{ item.name }}</span>
        </div>
        <div class="layer-item-action">
          <Icon
            type="arrow-right-c"
            title="放缩到图层"
            @click.native.stop="zoomToLayer(item)" />
          <Icon
            v-if="editable"
            type="trash-b"
            title="删除图层"
            @click.native.stop="delateLayer(item)" />
        </div>
      </div>
    </div>
    <Modal
      v-model="modalOpened"
      :mask-closable="false"
      width="800"
      class="layer-module-modal"
      title="选择地图图层"
      @on-ok="addLayers">
      <div>
        <div class="layer-search-panel">
          <Input
            v-model="layerKeyword"
            placeholder="输入服务名称..."
            style="width: 500px"
            @on-change="searchLayer"></Input>
          <Button
            type="primary"
            @click="searchLayer">查询</Button>
        </div>
        <div class="modal-title">
          <div class="res-data-wrapper">
            <DataTree
              :click-node-expand="false"
              directory
              accordion
              @on-current-select="selectTree">
            </DataTree>
            <Table
              :columns="tableColumns"
              :data="tableData"
              :loading="tableLoading"
              height="300"
              size="small"
              stripe
              border
              @on-selection-change="setSelectedLayers">
            </Table>
          </div>
        </div>
        <div class="layer-table-page">
          <Page
            :total="layerTotal"
            size="small"
            show-total
            @on-change="querylayers">
          </Page>
        </div>
      </div>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.layers-module-wrapper {
  width: 100%;
  height: calc(~'100vh - 120px');
  .dash-button {
    margin-left: 15%;
    width: 70%;
    height: 40px;
    border: 1px dashed #5d5d5d;
    border-radius: 2px;
    line-height: 37px;
    text-align: center;
    cursor: pointer;
    &:hover {
      border: 1px dashed #20a1ff;
    }
  }
  .dash-show {
    padding-left: 20px;
    margin-left: 5px;
    width: 95%;
    height: 30px;
    border-left: 4px solid #20a1ff;
    border-radius: 2px;
    line-height: 30px;
    color: #20a1ff;
  }

  .layer-list-wrapper {
    margin-top: 10px;
    margin-bottom: 15px;
    .layer-item {
      margin-top: 5px;
      background-color: #dddddd;
      border-radius: 3px;
      list-style: none;
      padding: 11px 8px;
      height: 44px;
      display: flex;
    }
    .layer-item-title {
      flex: 1;
      padding-left: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      .k-checkbox {
        left: -2px;
      }
    }
    .layer-item-action {
      flex: 1;
      text-align: right;
      .k-icon {
        margin: 0 4px;
        cursor: pointer;
        font-size: 16px;
        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
}

.layer-module-modal {
  .modal-title {
    .res-data-wrapper {
      display: flex;
    }
    .k-datatree {
      width: 150px;
    }
    .k-table-wrapper {
      flex: 1;
    }
  }
}

.layer-search-panel {
  margin-bottom: 15px;
  .k-input-wrapper {
    margin-right: 5px;
    width: 250px;
  }
}

.layer-table-page {
  text-align: right;
  margin-top: 10px;
}
</style>
